package org.zachary.prosocialbehaviorservice.infrastructure.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import org.zachary.prosocialbehaviorservice.domain.aggregate_model.activity_user.UserActivity;
import org.zachary.prosocialbehaviorservice.domain.aggregate_model.activity_user.UserJoinActivityDTO;

import java.util.List;

public interface SpringDataUserActivityRepository extends JpaRepository<UserActivity,Integer> {
    @Transactional
    @Modifying
    @Query("DELETE FROM UserActivity ua WHERE ua.userId = :userId and ua.activityId=:activityId")
    void deleteByUserIdAndActivityId(@Param("userId") Integer userId,@Param("activityId") Integer activityId);

    @Query("SELECT ua FROM UserActivity ua WHERE ua.userId = :userId")
    List<UserActivity> findByUserId(@Param("userId") Integer userId);
    @Transactional
    @Modifying
    @Query("UPDATE UserActivity ua SET ua.finished=true WHERE ua.userId=:userId and ua.activityId=:itemId")
    void finished( @Param("userId") Integer userId,@Param("itemId") Integer itemId);

    @Query("SELECT ua FROM UserActivity ua WHERE ua.userId = :userId AND ua.activityId=:itemId")
    UserActivity findByUserIdAndItemId(@Param("userId") Integer userId,@Param("itemId") Integer itemId);

    @Query(value = """
        SELECT new org.zachary.prosocialbehaviorservice.domain.aggregate_model.activity_user.UserJoinActivityDTO(
            a.id,
            ua.finished,
            a.title,
            a.content,
            a.startDate,
            a.endDate,
            a.publishDate,
            a.qrCode,
            a.number
        )
        FROM UserActivity ua
        JOIN ActivityItem a ON ua.activityId = a.id
        WHERE ua.userId = :userId
    """)
    List<UserJoinActivityDTO> findUserJoinedActivities(@Param("userId") Integer userId);
}
